class Nonogram {
    constructor(width = 5, height = 5) {
        this.width = width;
        this.height = height;
        this.grid = Array(height).fill().map(() => Array(width).fill(0));
        this.solution = Array(height).fill().map(() => Array(width).fill(0));
        this.rowHints = [];
        this.colHints = [];
        this.startTime = Date.now();
        this.generatePuzzle();
    }

    generatePuzzle() {
        // 生成随机解决方案，确保每行和每列至少有一个填充格子
        for (let i = 0; i < this.height; i++) {
            let hasFilledCell = false;
            for (let j = 0; j < this.width; j++) {
                if (Math.random() < 0.5) {
                    this.solution[i][j] = 1;
                    hasFilledCell = true;
                }
            }
            // 如果这一行没有填充格子，随机选择一个填充
            if (!hasFilledCell) {
                const randomCol = Math.floor(Math.random() * this.width);
                this.solution[i][randomCol] = 1;
            }
        }

        // 检查并确保每列至少有一个填充格子
        for (let j = 0; j < this.width; j++) {
            let hasFilledCell = false;
            for (let i = 0; i < this.height; i++) {
                if (this.solution[i][j] === 1) {
                    hasFilledCell = true;
                    break;
                }
            }
            // 如果这一列没有填充格子，随机选择一个填充
            if (!hasFilledCell) {
                const randomRow = Math.floor(Math.random() * this.height);
                this.solution[randomRow][j] = 1;
            }
        }
        
        this.rowHints = this.generateHints(this.solution);
        const transposed = this.solution[0].map((_, i) => 
            this.solution.map(row => row[i]));
        this.colHints = this.generateHints(transposed);
    }

    generateHints(lines) {
        return lines.map(line => {
            const hints = [];
            let count = 0;
            
            for (const cell of line) {
                if (cell === 1) {
                    count++;
                } else if (count > 0) {
                    hints.push(count);
                    count = 0;
                }
            }
            
            if (count > 0) {
                hints.push(count);
            }
            
            // 确保至少有一个提示数字
            return hints.length > 0 ? hints : [0];
        });
    }

    checkWin(playerGrid) {
        if (!playerGrid || playerGrid.length !== this.height) return false;
        return JSON.stringify(playerGrid) === JSON.stringify(this.solution);
    }

    getGameState() {
        return {
            rowHints: this.rowHints,
            colHints: this.colHints,
            width: this.width,
            height: this.height,
            timePlayed: Math.floor((Date.now() - this.startTime) / 1000)
        };
    }
}

module.exports = Nonogram; 